package com.idc.quotation.controller;

import java.util.Set;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.idc.common.cache.RedisClient;
import com.idc.common.cache.annotation.LimitType;
import com.idc.common.cache.annotation.RedisLimit;
import com.idc.common.constant.ErrorCode;
import com.idc.common.constant.RedisKey;
import com.idc.common.mvc.vo.ResponseVo;
import com.idc.common.util.AES;
import com.idc.common.util.LogUtil;
import com.idc.common.util.SecureRandomUtils;
import com.idc.quotation.config.LoginConfig;
import com.idc.quotation.dto.LoginDto;
import com.idc.quotation.dto.RegistrationDto;
import com.idc.quotation.service.LoginService;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
@RequestMapping("/login")
public class LoginController {
	@Autowired
	private LoginConfig loginConfig;

	private boolean isDev;

	@Value("${spring.profiles.active}")
	private String active;

	@PostConstruct
	public void initParams() {
		if ("dev".equals(active)) {
			isDev = true;
		} else {
			isDev = false;
		}
	}

	@Autowired
	private RedisClient redisClient;

	@Value("${login.smsCodeValiditySeconds:300}")
	private int smsCodeValiditySeconds;

	@RequestMapping("sendSmsCode")
	@RedisLimit(prefix = "loginSmsCode:", count = 2, period = 60, limitType = LimitType.PARAMS, argsIndex = 0, 
			code = ErrorCode.SMSCODE_FLOW_LIMIT_CODE, 
			failDesc = ErrorCode.SMSCODE_FLOW_LIMIT_DESC)
	public ResponseVo<?> sendSmsCode(String mdn) {
		LogUtil.info(log, "sendSmsCode:{}", mdn);
		try {
			mdn = AES.decryptForApp(mdn);
			String aesMdn = AES.encode(mdn);
			LogUtil.info(log, "aesMdn:{}", aesMdn);
		} catch (Exception e) {
			return ResponseVo.fail(ErrorCode.ERROR_PARAM);
		}
		Set<String> testAccount = loginConfig.getTestAccount();
		if (testAccount.isEmpty() || !testAccount.contains(mdn)) {
			return ResponseVo.fail(ErrorCode.ERROR_USER);
		}
		// 生产随机的四位数字，过期时间为60s
		String code = SecureRandomUtils.randomNumeric(4);
		if (testAccount.contains(mdn)) {
			code = mdn.substring(mdn.length() - 4, mdn.length());
		}
		redisClient.set(RedisKey.LOGIN_VERIFICATION_CODE + mdn, code, smsCodeValiditySeconds);
		String msg = "【翼可信】您正在登录翼可信报价系统,验证码为：" + code;
		LogUtil.info(log, msg);
		// 发送短信
		return ResponseVo.success();
	}

	@Autowired
	private LoginService loginService;

	@RequestMapping("smsCodeLogin")
	public ResponseVo<?> smsCodeLogin(@RequestBody LoginDto dto) {
		LogUtil.info(log, "收到登录请求：{}", JSON.toJSONString(dto));
		String mdn = null;
		String code = null;
		try {
			mdn = AES.decryptForApp(dto.getMdn());
			code = AES.decryptForApp(dto.getCode());
		} catch (Exception e) {
			return ResponseVo.fail(ErrorCode.ERROR_PARAM);
		}
		ResponseVo<?> login = loginService.smsCodeLogin(mdn, code);
		return login;
	}

	// @RequestMapping("registration")
	public ResponseVo<?> registration(@RequestBody RegistrationDto dto) {
		String mdn = dto.getMdn();
		String company = dto.getCompany();
		try {
			mdn = AES.decryptForApp(mdn);
			company = AES.decryptForApp(company);
			Long mdnLong = Long.parseLong(mdn);
			if (!(mdnLong > 10000000000L && mdnLong <= 19999999999L)) {
				return ResponseVo.fail(ErrorCode.ERROR_PARAM);
			}
			if (company.length() > 100) {
				return ResponseVo.fail(ErrorCode.ERROR_PARAM);
			}
		} catch (Exception e) {
			return ResponseVo.fail(ErrorCode.ERROR_PARAM);
		}
		redisClient.hset(RedisKey.LOGIN_REGISTRATION_HASH, mdn, company);
		LogUtil.info(log, "登记成功:{}", JSON.toJSONString(dto));
		return ResponseVo.success();
	}

}
